package deyi.struct;

import lombok.Getter;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UserDefinedList<T> implements Serializable,Iterable<T> {
    @Getter
    private List<T> list;

    public UserDefinedList(){
        list = new ArrayList<T>();
    }

    public Iterator<T> iterator() {
        return list.iterator();
    }

    public void addObj(T obj){
        synchronized (list){
            list.add(obj);
        }
    }

    public int getListSize(){
        int listSize = 0;
        synchronized (list){
            listSize = list.size();
        }
        return listSize;
    }

    public void removeAll(){
        synchronized (list){
            list.clear();
        }
    }

    public List<T> cloneList(){
        List<T> listNew = new ArrayList<T>();
        synchronized (list){
            try {
                listNew = deepCopy(list);
                list.clear();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return listNew;
    }

    public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        @SuppressWarnings("unchecked")
        List<T> dest = (List<T>) in.readObject();
        out.close();
        byteOut.close();
        in.close();
        byteIn.close();
        return dest;
    }
}
